package com.wims.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.wims.client.GreetingService;
import com.wims.data.PMF;
import com.wims.data.PersonType;
import com.wims.data.WIMSDatabase;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	boolean dbLoaded = false;
	WIMSDatabase wimsDB = null;
	
	private void checkLoadDb() {
		//anca: load the initial DB
		if(!dbLoaded) {
			wimsDB = new WIMSDatabase();
			wimsDB.initDataTypes();
			dbLoaded = true;
		}
	}
	
	public String greetServer(String input) {
		checkLoadDb();
		
		//anca: get all person types
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    String query = "select from " + PersonType.class.getName();
	    List<PersonType> personTypes = (List<PersonType>) pm.newQuery(query).execute();
	    
	    
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent
				+ "list of person types: "+personTypes.toString();
	}

	public ArrayList<String> getPersonTypes() {
		checkLoadDb();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    String query = "select from " + PersonType.class.getName();
	    List<PersonType> personTypes = (List<PersonType>) pm.newQuery(query).execute();
	    
	    ArrayList<String> result = new ArrayList<String>();
	    for (PersonType pt : personTypes)
	    	result.add(pt.getName());
	    return result;
	}
}
